extends Node


@export var bubbleScene : PackedScene

var rng = RandomNumberGenerator.new()

var running : bool
var gameOver : bool
var scroll
var score
const scrollSpeed : int = 1
var screenSize : Vector2i
var waterHeight : int
var bubbles : Array
var bubbleDelay : int = 100
var bubbleRange : int = 200

func _ready():
	screenSize = get_window().size
	waterHeight = $Water.get_node("Sprite2D").texture.get_height()
	rng.randomize()
	newGame()
	
func newGame():
	running = false
	gameOver = false
	score = 0
	scroll = 0
	$Score.text = str(score)
	bubbles.clear()
	$Player.reset()
	$Platform.reset()
	$GameOver.hide()
	get_tree().call_group("bubbles", "queue_free")
	
func _input(event):
	if gameOver == false:
		if Input.is_action_just_pressed("move_up"):
			if running == false:
				startGame()
				
func startGame():
	running = true
	$BubbleTimer.start()
	generateBubble()

func _process(delta):
	if running:
		scroll += scrollSpeed
		
	if scroll >= screenSize.x - 55:
		scroll = 0
		
	#$Water.position.x = -scroll
	
	for bubble in bubbles:
		if bubble == null:
			bubbles.erase(bubble)
		else:
			bubble.position.y -= scrollSpeed
	
func _on_bubble_timer_timeout() -> void:
	generateBubble()
	
func generateBubble():
	var bubble = bubbleScene.instantiate()
	bubble.scored.connect(scored)
	$BubbleSpawn.play()
	bubble.position.x = screenSize.x - rng.randi_range(40, 824)
	bubble.position.y = 790
	add_child(bubble)
	bubbles.append(bubble)
		
		
func scored():
	score += 1
	$Score.text = str(score)
	var r = rng.randf_range(0.0, 1.0)
	var g = rng.randf_range(0.0, 1.0)
	var b = rng.randf_range(0.0, 1.0)
	$Background.changeColor(r, g, b)
	$Water.changeColor(r, g, b)
	$Platform.changeColor(r, g, b)
	
	for bubble in bubbles:
		bubble.changeColor(r, g, b)

func stopGame():
	$Player.dead = true
	gameOver = true
	$BubbleTimer.stop()
	running = false
	$GameOver.show()
	
func _on_water_hit() -> void:
	$Player.dead = true
	stopGame()


func _on_game_over_restart() -> void:
	newGame()
